package com.crl.module.loaders
{
	import com.crl.module.loaders.workers.Worker;
	
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.ProgressEvent;
	import flash.net.URLRequest;
	
	public class AbstractQueueWorker extends Worker implements IQueueWorker
	{
		protected var pointer:int;
		
		protected var total:int;
		protected var loaded:int;
		
		protected var works:Array;
		
		private var _listener:IQueueWorkerListener;
		public function AbstractQueueWorker()
		{
		}
		
		
		public function get workListener():IQueueWorkerListener{
			return _listener;
		}
		public function set workListener(listener:IQueueWorkerListener):void{
			this._listener=listener;
		}
		
		
		override public function start() : void{
			_data=[];
			
			pointer=-1;
			loadNext();
		}
		
		
		public function loadNext():void
		{
			if(pointer<works.length-1){
				pointer++;
				
				this.loader=doLoad();
				var w:Worker=loader;
				w.addEventListener(Event.COMPLETE,itemCompleteHandler);
				w.addEventListener(ErrorEvent.ERROR,itemCompleteHandler);
				
			}else{
				this.onComplete(new Event(Event.COMPLETE));
			}
		}
		
		
		protected function itemCompleteHandler(event:Event):void{
			var w:Worker=event.currentTarget as Worker;
			if(event is ErrorEvent){
				
			}else{
				_data.push(w.data);
			}
			
			
			
			loaded++;
			if(_listener)_listener.onItemComplete(this,w.data,loaded);
			this.dispatchEvent(new ProgressEvent(ProgressEvent.PROGRESS,event.bubbles,event.cancelable,this.loaded,this.total));
	
			this.loadNext();
		}
		
		protected function doLoad():Worker{
			//todo override;
			return null;
		}
		
		
		public function get itemTotal():int
		{
			return this.total;
		}
		
		public function get itemLoaded():int
		{
			return this.loaded;
		}
		
		override public function load(request:URLRequest, autoStart:Boolean=false):void
		{
			throw new Error("queueWork 不能直接load");
		}
		
	}
}